package com.systemframework.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import com.systemframework.constants.Constants;
import com.systemframework.exception.ResultException;
import com.systemframework.properties.SaTokenProperties;
import com.systemframework.util.Base64ToMultipartFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author summer
 * @date 2023-03-22 14:01
 */
@Configuration
@Slf4j
public class FileUploadConfig {

    private SaTokenProperties saTokenProperties;

    @Autowired
    public void setSaTokenProperties(SaTokenProperties saTokenProperties) {
        this.saTokenProperties = saTokenProperties;
    }

    public String base64Upload(String base64){
        MultipartFile multipartFile = Base64ToMultipartFile.base64ToMultipart(base64);
        String originalFilename = multipartFile.getOriginalFilename();
        String format = FileNameUtil.extName(FileUtil.file(originalFilename));
        String newFileName = RandomUtil.randomNumbers(10);
        try {
            multipartFile.transferTo(FileUtil.file(saTokenProperties.getFilePath()+newFileName+ Constants.FILE_STATE_ID+format));
            return newFileName+ Constants.FILE_STATE_ID+format;
        } catch (IOException e) {
            log.error("file upload:{}",e.getMessage(),e);
            throw new ResultException(e.getMessage());
        }

    }
}
